<?php
namespace app\common\service\Users;

use app\common\entity\User;
use think\facade\Request;
use think\facade\Session;
use app\common\entity\UserVoucherLog;
use app\common\entity\UserJewelLog;
use app\common\entity\UserMagicLog;
use use app\admin\model\Config;
use app\common\service\Users\Identity;
use think\Db;

class Service
{
    /**
     * 加密前缀
     */
    const PREFIX_KEY = "eco_member";

    public function __construct()
    {
        $this->model = new User();
        $this->model_voucher = new UserVoucherLog();
        $this->model_jewel = new UserJewelLog();
    }

    /**
     * 加密函数
     */
    public function getPassword($password)
    {
        return md5(md5(self::PREFIX_KEY . $password));
    }

    /**
     * 验证密码
     */
    public function checkPassword($password, User $entity)
    {
        return $this->getPassword($password) === $entity->getPassword();
    }

    public function checkSafePassword($password, User $entity)
    {
        return $this->getPassword($password) === $entity->getSafePassword();
    }

    public function addUser($data)
    {
        $entity = new User();
        $entity->mobile = $data['mobile'];
        $entity->nick_name = $data['nick_name'];
        $entity->password = $this->getPassword($data['password']);
        $entity->trad_password = $this->getPassword($data['trad_password']);
        $entity->wx = $data['wx'] ?: '';
        $entity->zfb = $data['zfb'] ?: '';
        $entity->card_name = $data['card_name'] ?: '';
        $entity->card = $data['card'] ?: '';
        $entity->real_name = $data['real_name'] ?: '';
        $entity->card_id = $data['card_id'] ?: '';
        $entity->register_time = time();
        $entity->register_ip = $data['ip'] ?: Request::ip();
        $entity->status = User::STATUS_DEFAULT;
        $entity->is_certification = $data['is_certification'] ?: User::AUTH_SUCCESS;
        $entity->wx_image_url = $data['wx_image_url'] ?: '';
        $entity->zfb_image_url = $data['zfb_image_url'] ?: '';

        if ($entity->save()) {
            return $entity->getId();
        }

        return false;
    }

    public function updateUser(User $user, $data)
    {
        $user->nick_name = $data['nick_name'];
        if ($data['password']) {
            $user->password = $this->getPassword($data['password']);
        }

        if ($data['trad_password']) {
            $user->trad_password = $this->getPassword($data['trad_password']);
        }

        $user->wx = $data['wx'] ?: '';
        $user->zfb = $data['zfb'] ?: '';
        $user->card_name = $data['card_name'] ?: '';
        $user->card = $data['card'] ?: '';
        $user->real_name = $data['real_name'] ?: '';
        $user->card_id = $data['card_id'] ?: '';
        $user->is_certification = $data['is_certification'];
        $user->wx_image_url = $data['wx_image_url'] ?: '';
        $user->zfb_image_url = $data['zfb_image_url'] ?: '';

        return $user->save();
    }

    /**
     * 检查用户名是否已存在
     */
    public function checkMobile($name, $id = 0)
    {
        $entity = user::where('mobile', $name);
        if ($id) {
            $entity->where('id', '<>', $id);
        }
        return $entity->find() ? true : false;
    }

    /**
     * 银行卡号 微信号 支付宝账号 唯一
     */
    public function checkMsg($type, $account, $id = '')
    {
        return \app\common\entity\User::where("$type", $account)->where('id', '<>', $id)->find();
    }

    public function adjustVoucher($user,$number,$voucher,$reduce,$type=1,$text = '变更认筹券')
    {
        if ($number <= 0) {
            $this->error = '变更数量参数有误';
            return false;
        }
        if ($voucher <= 0) {
            $this->error = '变更认筹券数量参数有误';
            return false;
        }

        if ($reduce == 1 && $voucher > $user->voucher) {
            $this->error = '用户认筹券不足，请先充值';
            return false;
        }

        Db::startTrans();

        if ($reduce == 1) {
            $result = (new User())->where("id",$user->id)->setDec('voucher',$voucher);
        } else {
            $result = (new User())->where("id",$user->id)->setInc('voucher',$voucher);
        }
        if (!$result) {
            $this->error = (new User())->getError();
            Db::rollback();
            return false;
        }

        $number_val = $reduce == 1 ? -$voucher : $voucher;
        $new_val = $reduce == 1 ? bcsub($user->voucher,$voucher,6) : bcadd($user->voucher, $voucher,6);
        $log = [
            'user_id' => $user->id,
            'number' => $number_val,
            'old' => $user->voucher,
            'new' => $new_val,
            'number_fmi' => $number,
            'voucher_price' => Config::getValue('voucher_price'),
            'remark' => $text,
            'types' => (int) $type,
            'create_time' => time()
        ];
        $result = $this->model_voucher->save($log);
        if (!$result) {
            $this->error = $this->model_voucher->getError();
            Db::rollback();
            return false;
        }

        if ($type == 3) {
            $voucher_use = Config::where('key', 'voucher_use')->find();
            $voucher_use->value = bcadd($voucher_use->value, $number);
            $result = $voucher_use->save();
            if (!$result) {
                $this->error = '操作失败，请稍后再试！';
                Db::rollback();
                return false;
            }

            $result = (new User())->where("id",$user->id)->setInc('magic',$voucher);
            if (!$result) {
                $this->error = '操作失败，请稍后再试！';
                Db::rollback();
                return false;
            }

            $result = UserMagicLog::addInfo($user->id, '认筹券购买FMI币', $number, $user->magic, bcadd($number,$user->magic,8),10);
            if (!$result) {
                $this->error = '操作失败，请稍后再试！';
                Db::rollback();
                return false;
            }
        }

        (new Identity())->delCache($user->id);

        Db::commit();
        return true;
    }

    public function adjustJewel($user,$number,$reduce,$text = '变更动态钱包',$ispush = false)
    {
        if ($number <= 0) {
            $this->error = '变更数量参数有误';
            return false;
        }

        if ($reduce == 1 && $number > $user->jewel) {
            $this->error = '用户认筹券不足，请先充值';
            return false;
        }

        Db::startTrans();

        if ($reduce == 1) {
            $result = (new User())->where("id",$user->id)->setDec('jewel',$number);
        } else {
            $result = (new User())->where("id",$user->id)->setInc('jewel',$number);
        }

        if (!$result) {
            $this->error = (new User())->getError();
            Db::rollback();
            return false;
        }

        if ($ispush == true) {
            $result = (new User())->where("id",$user->id)->setInc('push_reward',$number);
            if (!$result) {
                $this->error = (new User())->getError();
                Db::rollback();
                return false;
            }
        }

        $jewel = $reduce == 1 ? -$number : $number;
        $new = $reduce == 1 ? bcsub($user->jewel,$number,6) : bcadd($user->jewel, $number,6);
        $result = $this->model_jewel->addInfo($user->id,$text,$jewel,$user->jewel,$new);
        if (!$result) {
            $this->error = $this->model_jewel->getError();
            Db::rollback();
            return false;
        }

        (new Identity())->delCache($user->id);

        Db::commit();
        return true;
    }

    // 认筹券充值返
    public function rechargeReward($user,$voucher)
    {
        $pids_arr = array_filter(explode('-',$user->pid_all));
        if (count($pids_arr) < 1) return true;

        DB::startTrans();

        $farrs = [
            Config::getValue('voucher_recharge_f1'),
            Config::getValue('voucher_recharge_f2'),
            Config::getValue('voucher_recharge_f3'),
            Config::getValue('voucher_recharge_f4'),
            Config::getValue('voucher_recharge_f5'),
        ];

        $pUsers = $this->model->where("id","in",$pids_arr)->order("register_time desc")->limit(5)->select();
        $save_datas = $save_logs = [];
        foreach ($pUsers as $k => $val) {
            if ($farrs[$k] <= 0) continue;
            $now_reward = bcdiv($voucher * $farrs[$k],100,6);
            $save_datas[] = [
                'id' => $val['id'],
                'jewel' => bcadd($val['jewel'],$now_reward,6),
                'push_count' => ($user->pid == $val['id']) ? bcadd($val['push_count'],$voucher,6) : $val['push_count'],
            ];
            $save_logs[] = [
                'user_id' => $val['id'],
                'remark' => '充值认筹劵返'. ++$k .'代动态钱包',
                'jewel' => $now_reward,
                'old' => $val['jewel'],
                'new' => bcadd($val['jewel'],$now_reward,6),
                'create_time' => time(),
            ];
        }

        $result1 = $this->model->saveAll($save_datas);
        $result2 = $this->model_jewel->saveAll($save_logs);
        if (!$result1 || !$result2) {
            Db::rollback();
            return false;
        }

        Db::commit();

        return true;
    }

}